﻿using Commons.Collections;
using NVelocity;
using NVelocity.App;
using NVelocity.Runtime;
using System;
using System.Collections.Generic;
using System.IO;
using System.Web.Mvc;
using V5_EShop._Class.Common;

namespace V5_CMSMvc4.Models.ViewEngine {

    public class NVelocityViewEngine : VirtualPathProviderViewEngine {
        private string theme_template = SiteHelper.TemplateDir;

        public NVelocityViewEngine() {
            var areas = new List<string>();
            areas.Add("~/areas/{2}/views/{1}/{0}.html");
            areas.Add("~/areas/{2}/views/{1}/shared/{0}.html");

            base.AreaViewLocationFormats = areas.ToArray();

            base.AreaMasterLocationFormats = areas.ToArray();

            base.AreaPartialViewLocationFormats = areas.ToArray();

            base.ViewLocationFormats = new string[]
            {
                "~/templates/"+theme_template+"/{1}/{0}.html",
                "~/templates/"+theme_template+"/shared/{0}.html"
            };
            base.MasterLocationFormats = new string[]
            {
                "~/templates/"+theme_template+"/{1}/{0}.html",
                "~/templates/"+theme_template+"/shared/{0}.html",
            };
            base.PartialViewLocationFormats = new string[]
            {
                "~/templates/"+theme_template+"/{1}/{0}.html",
                "~/templates/"+theme_template+"/shared/{0}.html"
            };
            base.FileExtensions = new string[]
            {
                "html",
                "vm"
            };
        }

        public override ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache) {
            controllerContext.RouteData.Values["controller"] = controllerContext.RouteData.Values["controller"].ToString().ToLower();
            return base.FindView(controllerContext, viewName.ToLower(), masterName, useCache);
        }

        protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath) {
            throw new NotImplementedException();
        }

        protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath) {
            return new NVelocityView(controllerContext, viewPath, masterPath);
        }
    }

    public class NVelocityView : IView {
        private ControllerContext _controllerContext;

        private string _viewTemplate = string.Empty;

        private string _masterTemplate = string.Empty;

        private VelocityEngine velocity = null;

        private string theme_template = SiteHelper.TemplateDir;

        public NVelocityView(ControllerContext controllerContext, string viewTemplate, string masterTemplate) {
            _controllerContext = controllerContext;
            _viewTemplate = viewTemplate;
            _masterTemplate = masterTemplate;
        }

        public void Render(ViewContext viewContext, TextWriter writer) {


            var controllerName = _controllerContext.RouteData.Values["controller"];

            var methedName = _controllerContext.RouteData.Values["action"];

            var viewPath = string.Empty;

            string templatePath = string.Empty;

            var aa = _viewTemplate.Substring(0, _viewTemplate.LastIndexOf("/")).ToLower();
            aa = aa.Substring(0, aa.LastIndexOf("/"));
            var bb = aa;
            templatePath = _controllerContext.HttpContext.Server.MapPath(aa).ToLower();

            viewPath = _viewTemplate.Substring(bb.Length + 1).ToLower();

            if (velocity == null) {
                velocity = new VelocityEngine();
            }

            ExtendedProperties props = new ExtendedProperties();
            props.AddProperty(RuntimeConstants.RESOURCE_LOADER, "file");
            props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, templatePath);
            props.AddProperty(RuntimeConstants.INPUT_ENCODING, "utf-8");
            props.AddProperty(RuntimeConstants.OUTPUT_ENCODING, "utf-8");
            props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_CACHE, false);
            props.AddProperty("file.resource.loader.modificationCheckInterval", (Int64)60);
            velocity.Init(props);

            var context = new VelocityContext();
            foreach (var dc in _controllerContext.Controller.ViewData) {
                context.Put(dc.Key, dc.Value);
            }

            Template template = velocity.GetTemplate(viewPath);
            StringWriter writer1 = new StringWriter();
            template.Merge(context, writer1);

            var s = writer1.ToString();
            s += @"<div align='center'><a href='http://www.v5soft.com' title='v5soft软件提供' target='_blank'>Powered by v5soft.com</a></div>";
            _controllerContext.HttpContext.Response.Write(s);
            _controllerContext.HttpContext.Response.End();
        }
    }
}